import { useState } from 'react'
import { Icon } from '@taroify/icons'
import { Cell, Grid, Image, Navbar } from '@taroify/core'
import { useCreation, useMemoizedFn, useRequest } from 'ahooks'
import Taro, { useLoad, usePageScroll, usePullDownRefresh } from '@tarojs/taro'
import { Button, Navigator, Swiper, SwiperItem, Text, View } from '@tarojs/components'

import styles from './index.module.scss'
import { listGoods } from '@/apis/goods'
import { catchify } from '@/utils/hackify'
import { useStorage } from '@/hooks/useStorage'
import { useUserStore } from '@/hooks/useUserStore'
import { useBindPhone } from '@/hooks/useBindPhone'

export default function Index() {
  const [, bindPhone] = useBindPhone()
  const [, setCurrGoods] = useStorage('goods')
  const [scrollTop, setScrollTop] = useState(0)
  const { city, province, isAuthed, login, getGeo, getUserInfo } = useUserStore()
  const opacity = useCreation(() => Math.min(Math.max(1 - (80 - scrollTop) / 80, 0), 1), [scrollTop])

  const { data, runAsync } = useRequest(listGoods, { manual: true })

  const fetchUserInfo = useMemoizedFn(async () => {
    await login()
    await getUserInfo()
  })

  const loadData = useMemoizedFn(async () => {
    getGeo()
    await catchify(fetchUserInfo)()
    await runAsync()
  })

  useLoad(() => {
    console.log('Page loaded.')

    loadData()
  })

  usePageScroll((e) => {
    setScrollTop(e.scrollTop)
  })

  usePullDownRefresh(async () => {
    await catchify(runAsync)()
    Taro.stopPullDownRefresh()
  })

  const handleGoods = (item: Data) => {
    setCurrGoods(item)

    Taro.navigateTo({
      url: `/pages/goods/detail?code=${item.code}`,
    })
  }

  return (
    <View className="page" style={`--opacity: ${opacity}`}>
      <View className="page-content pb-6">
        <Navbar className={styles.navbar} fixed safeArea="top" nativeSafeTop>
          <Navbar.NavLeft icon={<Icon classPrefix="icon" name="weizhi" />}>
            <Text>{city || province}</Text>
          </Navbar.NavLeft>
          <Navbar.Title style="opacity: var(--opacity)">
            <Text>上门洗车</Text>
          </Navbar.Title>
        </Navbar>

        <Swiper className={styles.banner} indicator-dots autoplay indicator-active-color="white" interval={5000}>
          <SwiperItem>
            <Image
              className="size-full"
              src="https://znckfile.baoxianyun.com/car-img/ac-mpwx-home-slide.png"
              mode="aspectFill"
            />
          </SwiperItem>
          <SwiperItem>
            <Image
              className="size-full"
              src="https://znckfile.baoxianyun.com/car-img/ac-mpwx-home-slide.png"
              mode="aspectFill"
            />
          </SwiperItem>
          <SwiperItem>
            <Image
              className="size-full"
              src="https://znckfile.baoxianyun.com/car-img/ac-mpwx-home-slide.png"
              mode="aspectFill"
            />
          </SwiperItem>
        </Swiper>

        <Cell.Group className="!mb-4 relative z-3 !-mt-5" inset>
          {isAuthed ? (
            <View>已登录</View>
          ) : (
            <Button
              className="px-4 py-3 flex items-center gap-3 bg-default border-0 rounded-lg shadow-lg"
              hover-class="bg-hover"
              open-type="getPhoneNumber"
              onGetPhoneNumber={bindPhone}
            >
              <View className="size-12 p-2 flex flex-center text-grey bg-grey rounded-full">
                <Icon classPrefix="icon" name="wode" size="24" />
              </View>

              <Text className="text-lg">立即登录</Text>
            </Button>
          )}
        </Cell.Group>

        <Cell.Group className="!mb-4" inset style="--cell-group-background-color:var(--color-bg)">
          <Grid columns={2} clickable>
            {data?.map((item) => (
              <Grid.Item
                icon={<Image src={item.smallPic} mode="aspectFit" width="128px" height="96px" />}
                text={item.name}
                onClick={() => handleGoods(item)}
              />
            ))}
          </Grid>
        </Cell.Group>

        <Cell.Group className="!mb-4" title="优惠活动" inset>
          <Navigator hover-class="bg-hover" url="/pages/coupon/index">
            <Image
              className="w-full"
              src="https://znckfile.baoxianyun.com/car-img/ac-mpwx-offer-coupon.png"
              height="110px"
              mode="aspectFill"
            />
          </Navigator>
        </Cell.Group>
      </View>
    </View>
  )
}
